import random
import pygame
import sys
from pygame.locals import *
import time
#初始化区
# 由于我们的贪吃蛇是有大小尺寸的, 因此地图的实际尺寸是相对于贪吃蛇的大小尺寸而言的
Window_Width = 800
Window_Height = 500
Cell_Size = 20
Cell_W = int(Window_Width / Cell_Size)
Cell_H = int(Window_Height / Cell_Size)
#颜色定义
White = (255, 255, 255)
Black = (0, 0, 0)
Red = (255, 0, 0)
Green = (0, 255, 0)
DARKGreen = (0, 155, 0)
DARKGRAY = (40, 40, 40)
YELLOW = (255, 255, 0)
Red_DARK = (150, 0, 0)
BLUE = (0, 0, 255)
BLUE_DARK = (0, 0, 150)

'''定义一个蛇类'''
class snake(object):
    #初始化需要用的属性
    def __init__(self):
        self.Cell_Size = 20
        self.Cell_W = int(Window_Width / Cell_Size)
        self.Cell_H = int(Window_Height / Cell_Size)
        # 随机初始化设置一个点作为贪吃蛇的起点
    def start_point(self):
        startx = random.randint(10, self.Cell_W - 6)
        starty = random.randint(10, self.Cell_H - 6)
        wormCoords = [{'x': startx, 'y': starty},
                      {'x': startx - 1, 'y': starty},
                      {'x': startx - 2, 'y': starty}]
        return wormCoords

    # 以这个点为起点，画一条长度为3格的贪吃蛇（数组）
    def draw_Worm(self,wormCoords):
        for coord in wormCoords:
            x = coord['x'] * self.Cell_Size
            y = coord['y'] * self.Cell_Size
            wormSegmentRect = pygame.Rect(x, y, self.Cell_Size,self.Cell_Size)
            pygame.draw.rect(screen,BLUE, wormSegmentRect)
            wormInnerSegmentRect = pygame.Rect( x , y , Cell_Size , Cell_Size )
            pygame.draw.rect(screen, Green, wormInnerSegmentRect)

#定义一个食物类
class food(object):
    def __init__(self):
        self.Cell_Size = 20
        self.Cell_W = int(Window_Width / Cell_Size)
        self.Cell_H = int(Window_Height / Cell_Size)
    #把食物画出来
    def draw_food(self,coord):
        x = coord['x'] * self.Cell_Size
        y = coord['y'] * self.Cell_Size
        appleRect = (x, y, self.Cell_Size, self.Cell_Size)
        pygame.draw.rect(screen,Red, appleRect)
    #当蛇吃掉食物后，随机在出现一个食物
    def eat_food(self):
        return {'x': random.randint(0, Cell_W - 1), 'y': random.randint(0, Cell_H - 1)}

#定义移动类
class move(object):
    def __init__(self,wormCoords,f):
        self.wormCoords = wormCoords
        self.direction = 'right'
        self.f = food()
    #键盘控制
    def key_control(self):
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == KEYDOWN:
                if (event.key == K_LEFT) and self.direction != 'right':
                    self.direction = 'left'
                elif (event.key == K_RIGHT) and self.direction != 'left':
                    self.direction = 'right'
                elif (event.key == K_UP) and self.direction != 'down':
                    self.direction = 'up'
                elif (event.key == K_DOWN) and self.direction != 'up':
                    self.direction = 'down'

    #方向
    def direct(self):
        if self.direction == 'up':
            n = {'x': self.wormCoords[0]['x'],'y': self.wormCoords[0]['y'] - 1}
        elif self.direction == 'down':
            n = {'x': self.wormCoords[0]['x'],'y': self.wormCoords[0]['y'] + 1}
        elif self.direction == 'left':
            n = {'x': self.wormCoords[0]['x'] - 1, 'y': self.wormCoords[0]['y']}
        elif self.direction == 'right':
            n = {'x': self.wormCoords[0]['x'] + 1, 'y': self.wormCoords[0]['y']}
        self.wormCoords.insert(0, n)
def runGame():
    f = food()
    s = snake()
    wormCoords = s.start_point()
    de = move(wormCoords,f)
    apple = f.eat_food()
    while True:
        de.key_control()
        if wormCoords[0]['x'] == -1 or wormCoords[0]['x'] == Cell_W or wormCoords[0]['y'] == -1 or \
                wormCoords[0]['y'] == Cell_H:
            return
        for i in wormCoords[1:]:
            if i['x'] == wormCoords[0]['x'] and i['y'] == wormCoords[0]['y']:
                return
        if wormCoords[0]['x'] == apple['x'] and wormCoords[0]['y'] == apple['y']:
            apple = f.eat_food()
        else:
            del wormCoords[-1]
        de.direct()
        screen.fill((0, 0, 0))#初始化窗口，使得消除移动轨迹
        screen.blit(background, (0, 0))
        # for x in range(0, Window_Width, Cell_Size):
        #     pygame.draw.line(screen, (255, 255, 255), (x, 0), (x, Window_Height))
        # for y in range(0, Window_Height, Cell_Size):
        #     pygame.draw.line(screen, (255, 255, 255), (0, y), (Window_Width, y))
        s.draw_Worm(wormCoords)
        f.draw_food(apple)
        pygame.display.update()
        time.sleep(0.1)
def main():
    global screen
    global background
    screen = pygame.display.set_mode((Window_Width, Window_Height))
    pygame.display.set_caption("贪吃蛇小游戏")
    background = pygame.image.load('./pictures/greed.png')

    while True:
        runGame()
        screen.blit(background,(0,0))
        pygame.display.update()
if __name__ == '__main__':
    main()